//
//  QDLifeWebViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/5/10.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 惠周边的webView
final class QDLifeWebViewController: QDWebViewController {

    override func autoRequestUrlAtViewDidLoad() -> Bool { return false }
    override var messageHanderNames: [String]? { return ["couponInterface"] }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        webView.uiDelegate = self
        //请求惠周边
        requestDiscount()
    }
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension QDLifeWebViewController: WKScriptMessageHandler,WKUIDelegate {
    
    /// user
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        let name = message.name
        //如果是约定好的interface
        guard name == "couponInterface",let functionName = message.body as? String else { return }
        
        //如果是getInterData
        if functionName == "getInterData" {
         
            //执行js
            webView.evaluateJavaScript("getinfo('\(parameterString)')") { (data, error) in
                
                print("\(error)")
                
                let i = 0
                
            }
            
//            webView.evaluateJavaScript("alert(`ok`)") { (data, error) in
//
//                print("\(error?.localizedDescription)")
//
//                let i = 0
//
//            }
        }
    }
    
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        let message = message
        
        let i = 0
        let alertController = UIAlertController(title: "调试", message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "确定", style: .cancel, handler: { (action) in }))
        present(alertController, animated: true, completion: nil)
        
        completionHandler()
        
    }

}



extension QDLifeWebViewController {
    
    /// 请求生活圈信息
    @objc func requestDiscount(){
        
        checkLogin {[weak self] in //进行登录检测
            
            let phone = (QDUserInfoModelObjc.phone as NSString).des_encrypt()/*("18706480675" as NSString).des_encrypt()*/
            QDNetworkingManager.request(url: discountInLifeUrl, paramteres: ["phone":phone], success: { (msg, data) in
                
                guard let url = data["url"] as? String else { return }
                
                self?.url = url
                self?.requestUrl()
                
            },errorHandler: { (msg, errorType) in
                
                self?.view.showTextHUD(text: "msg")
            })
        }
    }
    
    /// 开始请求
    override func requestUrl() {
        
        //追加cookie
        guard let urlString = self.url, let url = URL(string: urlString) else { return }
        
        var request = URLRequest(url: url)
        request.addValue(parameterString as String, forHTTPHeaderField: "Cookie")
        webView.load(request)
    }
    
    
    /// 参数
    var parameterString: NSString {
        get {
        
            let parameters = ["phoneNo" : (QDUserInfoModelObjc.phone as NSString).des_encrypt(),//加密手机号
                            "longitude" : QDLocationManager.longitude().stringValue,//经度
                            "latitude" : QDLocationManager.latitude().stringValue]//纬度
            
            guard  let data = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return ""}
            guard let strJson = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return "" }
            
            return strJson
        }
    }
}
